<template>
<div class="player">
  <normalPlay :totaltime="totalTime" :currentTime="currentTime"></normalPlay>
  <MiniPlay @showList="show"></MiniPlay>
  <PlayList ref="playlist"></PlayList>
  <audio :src="currentSongs.url" ref="audio" @timeupdate="timeupdate" @ended="end"></audio>
</div>
</template>

<script>
import normalPlay from '../components/Player/normalPlay'
import MiniPlay from '../components/Player/MiniPlay'
import PlayList from '../components/Player/PlayList'
import modeType from '../store/modeType'
import { mapGetters, mapActions } from 'vuex'
import { getRandomIntInclusive } from '../../tools/tools'
export default {
  name: 'player',
  components: {
    normalPlay,
    MiniPlay,
    PlayList
  },
  computed: {
    ...mapGetters([
      'isPlay',
      'currentSongs',
      'currentIndex',
      'currentTimes',
      'mode',
      'songs'
    ])
  },
  data: function () {
    return {
      totalTime: 0,
      currentTime: 0
    }
  },
  methods: {
    ...mapActions([
      'setIndexs',
      'sethistorySong'
    ]),
    show () {
      this.$refs.playlist.show()
    },
    timeupdate (e) {
      // console.log(e.target.currentTime)
      this.currentTime = e.target.currentTime
    },
    end (e) {
      if (this.mode === modeType.loop) {
        this.setIndexs(this.currentIndex + 1)
      } else if (this.mode === modeType.one) {
        this.$refs.audio.play()
      } else if (this.mode === modeType.random) {
        const index = getRandomIntInclusive(0, this.songs.length - 1)
        this.setIndexs(index)
      }
    }

  },
  mounted () {
    this.$refs.audio.oncanplay = () => {
      this.totalTime = this.$refs.audio.duration
    }
  },
  watch: {
    isPlay (newValue, oldValue) {
      if (newValue) {
        this.sethistorySong(this.currentSongs)
        setTimeout(() => {
          this.$refs.audio.play()
        }, 100)
      } else {
        this.$refs.audio.pause()
      }
    },
    currentIndex () {
      this.$refs.audio.oncanplay = () => {
        this.sethistorySong(this.currentSongs)
        this.totalTime = this.$refs.audio.duration
        if (this.isPlay) {
          this.$refs.audio.play()
        } else {
          this.$refs.audio.pause()
        }
      }
    },
    currentTimes (newValue, oldValue) {
      this.$refs.audio.currentTime = newValue
    }
  }
}
</script>

<style scoped lang="scss">
.player{
  position: fixed;
  /*top: 0;*/
  /*left: 0;*/
  /*bottom: 0;*/
  /*right: 0;*/
  /*background: pink;*/
}
</style>
